<?php

namespace App\Common;

use OSS\OssClient;
use OSS\Core\OssException;

use Config;

class AliossHandler
{
    public static function upload($type, $ext)
    {
        $file = $_FILES['file'];
        $fileName  = (mt_rand(0,999999) + time()).$ext;
        $path = self::getPath($type);

        $ossId   = Config::get('app.aliyun')['Appid'];
        $ossKey  = Config::get('app.aliyun')['Appkey']; 
        $postUrl = Config::get('app.aliyun')['Posthost'];
        $bucket = Config::get('app.aliyun')['Bucket'];

        $ossClient = new OssClient($ossId, $ossKey, $postUrl);
        $res = $ossClient->uploadFile($bucket, $path.$fileName, $file["tmp_name"]);
        $data = [
            'code' => 20000,
            'origin' => $fileName,
            'url' => Config::get('app.aliyun')['Host'].'/'.$path.$fileName
        ];
        if ($type == 'avatar') return $data['url'];

        return response()->json($data);
    }

    private static function getPath($type)
    {
        $path = '';
        
        switch ($type) {
            case 'good':
                $path = 'good/';
                break;
            case 'banner':
                $path = 'banner/';
                break;
            case 'notice':
                $path = 'notice/';
                break;
            case 'avatar':
                $path = 'avatar/';
                break;
        }

        return $path;
    }

    public static function read($type, $fileName)
    {
        $path = self::getPath($type);
        $ext = explode('.', $fileName)[1];
        if (in_array('$ext', ['png', 'PNG'])) {
            $ftype = "png";
        } else {
            $ftype = "jpg";
        }
        $end = "?x-oss-process=image/interlace,1/format,$ftype";

        return Config::get('app.aliyun')['Host']."/".$path.$fileName.$end;
    }
}
